<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Jobs\SavePandaFans;
use App\Models\PandaFans;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class PandaFansController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index(Request $request)
  {
    $validator = \Validator::make($request->all(), [
      'display_all' => 'sometimes|required|boolean',
      'sex' => 'sometimes|required|in:0,1,2',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    if($request->display_all) {
      $fans = PandaFans::where('sex', $request->sex)->paginate(10000);
      return $this->success(0, '', $fans);
    }
    $totalCount = PandaFans::count();
    $usedCount = PandaFans::where('is_used', true)->count();
    $maleCount = PandaFans::where('sex', '1')->count();
    $femaleCount = PandaFans::where('sex', '0')->count();
    $fans = PandaFans::where('name', 'like', '%' . $request->name . '%')
      ->where('phone', 'like', '%' . $request->phone . '%')
      ->paginate(10)
      ->toArray();
    $fans['totalCount'] = $totalCount;
    $fans['usedCount'] = $usedCount;
    $fans['maleCount'] = $maleCount;
    $fans['femaleCount'] = $femaleCount;
    return $this->success(0, '请求成功', $fans);
  }

  public function getOne(Request $request)
  {
    $fans = PandaFans::where(['is_used' => false])->first();
    if ($fans) {
      $data = $fans->toArray();
      $fans->is_used = true;
      $fans->save();
      return $this->success(0, 'OK', $data);
    }
    return $this->failure(-1, 'no data');
  }

  public function setSex(Request $request, $fans_id)
  {
    $validator = Validator::make($request->all(), [
      'sex' => 'required|numeric',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $data = $request->only('sex');
    $fans = PandaFans::find($fans_id);
    if ($fans) {
      $fans->sex = $data['sex'];
      $fans->save();
      return $this->success(0, '更新成功', $fans);
    }
    return $this->failure(0, '没有找到粉丝数据');
  }

  public function setExists(Request $request, $fans_id)
  {
    $validator = Validator::make($request->all(), [
      'is_exists' => 'required|boolean',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $data = $request->only('is_exists');
    $fans = PandaFans::find($fans_id);
    if ($fans) {
      $fans->is_exists = $data['is_exists'];
      $fans->save();
      return $this->success(0, '更新成功', $fans);
    }
    return $this->failure(0, '没有找到粉丝数据');
  }

  public function setCertification(Request $request, $fans_id)
  {
    $validator = Validator::make($request->all(), [
      'is_certification' => 'required|boolean',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $data = $request->only('is_certification');
    $fans = PandaFans::find($fans_id);
    if ($fans) {
      $fans->is_certification = $data['is_certification'];
      $fans->save();
      return $this->success(0, '更新成功', $fans);
    }
    return $this->failure(0, '没有找到粉丝数据');
  }

  public function setUsed(Request $request, $fans_id)
  {
    $validator = Validator::make($request->all(), [
      'used' => 'required|boolean',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $data = $request->only('used');
    $fans = PandaFans::find($fans_id);
    if ($fans) {
      $fans->is_used = $data['used'];
      $fans->save();
      return $this->success(0, '更新成功', $fans);
    }
    return $this->failure(-1, '没有找到粉丝数据');
  }

  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $validator = \Validator::make($request->all(), [
      'p' => 'required',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $dec_data = $this->decrypt($request->p);
    if(!$dec_data) {
      return $this->failure(-1, '数据错误或没有提供数据');
    }
    dispatch(new SavePandaFans($dec_data)); //->delay(Carbon::now()->addMinutes(1)) 延迟 1 分钟后处理队列
    return $this->success(0, '');
  }

  private function decrypt($str)
  {
    $s = substr($str, 7);
    $s = base64_decode($s);
    $arr = explode('&', $s);
    $data = [];
    foreach ($arr as $item) {
      $exp = explode('=', $item);
      $data[$exp[0]] = $exp[1];
    }
    return $data;
  }

  public function batchUpload(Request $request)
  {
    $type = $request->type;
    if ($request->hasFile('fans')) {
      if ($request->file('fans')->isValid()) {
        $path = $request->file('fans')->store('fans');
        $content = Storage::get($path);
        $n = 0;
        $data = [];
        if ($content) {
          $array = explode("\r\n", $content);
          $array = array_filter($array);
          $array_length = count($array);
          for ($i = 0; $i < $array_length; $i++) {
            $tempdata = explode('----', trim($array[$i]));
            $sex = '2';
            if(isset($tempdata[2])) {
              if($tempdata[2] == '女') {
                $sex = '0';
              } elseif($tempdata[2] == '男') {
                $sex = '1';
              }
            }
            $data[$n]['phone'] = $tempdata[0];
            $data[$n]['name'] = $tempdata[1];
            $data[$n]['sex'] = $sex;
            $data[$n]['type'] = $type; // 类型 1：微信；2：支付宝
            $data[$n]['created_at'] = date('Y-m-d H:i:s');
            $n++;
          }
          $count = count($data);
          if($count > 10000) {
            $splick_count = floor(count($data)/1000);
            if ($splick_count<= 0) $splick_count = 1;
            $new_arr = array_chunk($data, $splick_count);
            foreach ($new_arr as $item) {
              PandaFans::insertOnDuplicateKey($item);
            }
          } else {
            PandaFans::insertOnDuplicateKey($data);
          }
          return $this->success(0, '上传成功！');
        }
        return $this->failure(-1, '文件内容为空！');
      }
    }
    return $this->failure(-1, '没有上传任何文件！');
  }

  public function destroy($id)
  {
    PandaFans::destroy($id);
    return $this->success(0, '删除成功');
  }

  public function export(Request $request)
  {
    $sex = $request->sex;
    $ext = '所有';
    $date = date('Y年m月d日');

    if($sex != -1) {
      if($sex == 1) {
        $ext = '男';
      } else {
        $ext = '女';
      }
      $fans = PandaFans::where(['sex' => $sex])->get();
    } else {
      $fans = PandaFans::get()->toArray();
    }
    $filename = '粉丝数据-' . $date . '-' . $ext . '.txt';
    $encoded_filename = urlencode($filename);
    $encoded_filename = str_replace("+", "%20", $encoded_filename);
    header("Content-Type: application/octet-stream");
    if (preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])) {
      header('Content-Disposition:  attachment; filename="' . $encoded_filename . '"');
    } elseif (preg_match("/Firefox/", $_SERVER['HTTP_USER_AGENT'])) {
      header('Content-Disposition: attachment; filename*="utf8' . $filename . '"');
    } else {
      header('Content-Disposition: attachment; filename="' . $filename . '"');
    }
    foreach ($fans as $fan) {
      if($fan['sex'] == 1) {
        $sex = '男';
      } elseif($fan['sex'] == 0) {
        $sex = '女';
      } else {
        $sex = '未知';
      }
      echo $fan['phone'] . '----' . $fan['name'] . '----' . $sex . "\r\n";
    }
  }

  public function deleteAll()
  {
    PandaFans::truncate();
    return $this->success(0, '');
  }
}
